/**
 *
 * @Author:   tiannanyihao
 * @Date:     2019-07-01 14:22
 * @Profile:  request
 * @Project:  byf

 * @Description:
 *
 */

import axios from 'axios'
import Cookie from 'js-cookie'
import JsEncrypt from 'jsencrypt'
import { BASE_URL, IS_DEV } from '../env/env'

const requestBase = axios.create({
  baseURL: BASE_URL,
  timeout: 1000 * 15,
  headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, //添加请求头
})

/*添加请求前拦截处理*/
requestBase.interceptors.request.use((request) => {
    console.log('req=======>')
    console.log(request)

    let token, pub_key
    if (IS_DEV) {
      token = '820928bbc7ed58bacb1311625f8a4e56'
      pub_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdG4ZTbkj7wQx/4Jy8k4eYJWOf5H28bwri/ucOVIVjIrmwfmk33Xobma+uk4VD/QiPrym5D7taQnVKo6xjvX3eSwyNO3XZ2YrGp6zV8L0ADfO6JB0FXSFBMRA8b0AsQGXxIyRB/CEhn4Hwzaoc/wSMLIR1VAVgjEI3Pk0WfrSQzQIDAQAB'
    } else {
      token = Cookie.get('token')
      pub_key = Cookie.get('publicKey')
    }

    // 设置token
    request.headers.token = token
    // 公钥机密报文
    let RSA_String = publick_key_rsa(request.data, pub_key)
    // 数据转码,便于后端java解析
    request.data = encodeURIComponent(RSA_String)

    return request
  },
  error => {
    return Promise.reject(error)
  },
)

/*添加返回前拦截处理*/
requestBase.interceptors.response.use((res) => {

    return ResponseCodeHandle(res)
  },
  error => {
    return Promise.reject(error)
  })

/*响应码处理*/
const ResponseCodeHandle = (res) => {
  console.log('res=======>')
  console.log(res)

  return Promise.resolve(res)
}

/**************************************** FUNC_TOOL ****************************************/

/*将对象转换为form表单格式字符串*/
const getFromDataString = (data) => {

  let keyArr = []
  let valueArr = []
  Object.keys(data).forEach((key) => {
    keyArr.push(key)
    valueArr.push(data[key])
  })

  let fromDataString = ''
  for (let i = 0; i < keyArr.length; i++) {
    fromDataString += keyArr[i] + '=' + valueArr[i] + '&'
  }
  return fromDataString
}

/*公钥加密*/
const publick_key_rsa = (data, pub_key) => {
  // 加密
  let jes = new JsEncrypt()
  jes.setPublicKey(pub_key)

  // 分段, 防止参数长度超过公钥长度,造成加密失败
  let loops = Math.ceil(data.length / 37)
  let separatedStrings = []
  for (let i = 1; i <= loops; i++) {
    let charters = data.slice(i * 37 - 37, i * 37)
    separatedStrings.push(jes.encrypt(charters))
  }
  let RSA_String = separatedStrings.join(',');

  // fome表单格式化
  let fomeDataString = getFromDataString({'data': RSA_String})
  return fomeDataString
}

export default requestBase
